<template>
    <div class="check-item">
        <modal :loading="loading" :show.sync="innerShow" :id="id ? id : 'check-item'">
            <template slot="header">
                <span>{{itemID ? `CHECKLIST-${model}#${itemID}` : `Templates-${model}#${this.data.id}`}}</span>
            </template>
            <template slot="body">
                <div v-if="itemID">
                    <p class="title add-btn" @click="enableAddCheckList = !enableAddCheckList">
                        <i class="fif fif-add-list" style="margin-right: 5px;"></i>
                        <span>Add Checklist</span>
                    </p>
                    <div class="add-content" :class="{'show': enableAddCheckList}">
                        <MySelect
                                v-if="innerShow"
                                :id="this.data.id + 'templates'"
                                v-model="templateID"
                                :options="[]"
                                :searchable="true"
                                :ajax="ajaxConf"
                                placeholder="templates"
                        >
                        </MySelect>
                        <div class="btn-wrapper">
                            <button class="btn btn-sm btn-success" @click="saveCheckList">Save</button>
                            <button type="button" class="icon" @click="enableAddCheckList = false">×</button>
                        </div>
                    </div>
                </div>

                <div  :key="'checklist' + index" v-for="(checklist, index) in checkLists">
                    <p class="title" style="display: flex;justify-content: center;">
                        <i class="fif fif-check-bill" style="margin-right: 5px;"></i>
                        <EditableInput action="edit" :value="checklist.name" style="flex: 1;"
                                       @save="$emit('save', $event)"></EditableInput>
                        <i v-if="itemID && !checklist.checklist_items.length" class="fif fif-delete text-danger" style="cursor: pointer;margin-right:10px;" @click="removeCheckList(checklist)"></i>
                    </p>
                    <div style="padding: 0 10px;">
                        <div style="display: flex; justify-content: center; align-items: center;">
                            <span class="percent-text">{{checklist.completion_percent + '%'}}</span>
                            <div class="progress" style="flex: 1;height: 8px">
                                <div class="progress-bar" role="progressbar"
                                     aria-valuemin="0" aria-valuemax="100" :style="{width: checklist.completion_percent + '%'}">
                                </div>
                            </div>
                        </div>

                        <div  :key="'list' + index" class="list-items" style="margin-bottom: 8px;"
                             v-for="(item, index) in checklist.checklist_items"
                        >
                            <div style="display: flex;justify-content: center;">
                                <div @click="toggleCompleted(item)">
                                    <checkbox name="terms" :value="item.is_completed" v-model="item.is_completed" :disabled="!itemID"></checkbox>
                                </div>
                                <EditableInput :done="item.is_completed" action="edit" :value="item.item_name"
                                               @save="save(item, $event)"
                                               style="flex: 1;margin-left: 5px;margin-top: -3px;"></EditableInput>
                                <i v-if="!itemID" class="fif fif-delete text-danger" style="cursor: pointer;" @click="remove(item)"></i>
                                <i v-else-if="item.is_completed"  style="border-radius:4px;font-size: 12px;transform: scale(0.8);padding: 4px;background-color: #4caf50;color:#fff;font-weight: 700">{{item.completed_by}}</i>

                            </div>
                        </div>
                        <EditableInput action="add" @add="add(checklist, $event)"></EditableInput>
                    </div>
                </div>


                <div v-if="itemID">
                    <p class="title add-btn" @click="enableAddActive = !enableAddActive">
                        <i class="fif fif-add-remark" style="margin-right: 5px;"></i>
                        <span>Add Activity</span>
                    </p>

                    <div class="add-content" :class="{'show': enableAddActive}">
                        <input type="text" v-model="title" placeholder="Title" class="form-control"
                               style="margin-bottom: 10px;"/>

                        <textarea cols="30" class="form-control"
                                  style="height: 100px;resize: vertical;margin-bottom: 10px;"
                                  placeholder="Description" v-model="desc"></textarea>

                        <vue2-dropzone ref="myVueDropzone" id="myVueDropzone" :options="dropzoneOptions"
                                       @vdropzone-files-added="addedFiles"
                                       @vdropzone-removed-file="removeFile"
                        >

                        </vue2-dropzone>

                        <div class="btn-wrapper">
                            <button class="btn btn-sm btn-success" @click="saveActive">Save</button>
                            <button type="button" class="icon" @click="enableAddActive = false">×</button>
                        </div>
                    </div>
                </div>

                <div v-if="itemID">
                    <p class="title">
                        <i class="fif fif-list-column" style="margin-right: 5px;"></i>
                        <span>Activity</span>
                    </p>

                    <div class="active-items">
                        <div  :key="'active' + index" class="active-item" v-for="(item, index) in activeItems">
                            <p class="title">
                                {{item.title}}
                                <span class="time">{{item.date}}</span>
                                <i v-if="item.added_by__username"  style="margin-right: 5px;border-radius:4px;font-size: 12px;transform: scale(0.8);padding: 4px;background-color: #1e88e5;color:#fff;font-weight: 700;    float: right;">{{item.added_by__username}}</i>
                            </p>
                            <div class="img-wrapper" style="display: flex; align-items: center;">
                                <a   :key="'url' + index" :href="img.url" target="_blank" v-for="(img, index) in handleURL(item.attachment_links)" style="display: inline-block;max-width: 100px;margin-right: 10px;">
                                    <img :src="img.url" alt="" width="100%;">
                                </a>
                            </div>
                            <p class="desc">
                                <EditableInput action="edit" :value="item.text"
                                               @save="updateActiveItem(item, $event)"></EditableInput>
                            </p>
                        </div>
                    </div>
                </div>


            </template>
            <template slot="footer">
                <div></div>
            </template>
        </modal>
    </div>
</template>

<script>
    import ShowSync from '@/mixins/ShowSync'
    import Modal from '@/components/widgets/Modal'
    import EditableInput from '@/components/widgets/EditableInput'
    import 'vue2-dropzone/dist/vue2Dropzone.min.css'
    import vue2Dropzone from 'vue2-dropzone'
    import MySelect from '@/components/widgets/MySelect'
    import {searchModel, addModel, updateModel, deleteModel} from "@/api/model";
    import swal from 'sweetalert'
    //import moment from 'moment'
    import {getUploadInfo, uploadFileToOss, notifyFileUploadComplete} from "@/api/upload";
    import config from '@/config'
    import {getCookie} from '@/utils'
    import {createChecklistFromTemplate} from "@/api/notification";

    export default {
        name: "CheckItem",
        mixins: [ShowSync],
        components: {Modal, EditableInput, vue2Dropzone, MySelect},
        props: ['show', 'data', 'model', 'id', 'itemID'],
        data() {
            return {
                loading: false,
                enableAddCheckList: false,
                templateID: '',
                checkLists: [],
                enableAddActive: false,
                files: [],

                title: '',
                desc: '',

                activeItems: []

            }
        },
        created() {
            this.ajaxConf = {
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                delay: 250,
                type: 'POST',
                dataType: 'json',
                xhrFields: {withCredentials: true},
                url: config.serverURI + config.api.model_opt + `CheckList/search`,
                data: (params) => {
                    let search_keys = {}
                    search_keys[`name__icontains`] =  params.term
                    search_keys['model_name'] =  this.model
                    search_keys['is_template'] =  true

                    let query = {
                        search_keys: search_keys,
                        page_size: 200,
                    }
                    // Query parameters will be ?search=[term]&type=public
                    return JSON.stringify(query);
                },
                beforeSend: (xhr) => {
                    xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'))
                },
                processResults: (data) => {
                    return {
                        results: data.list.map(item => {
                            return {
                                id: item['id'],
                                text: item['name']
                            }
                        })
                    }

                }
            }
            this.dropzoneOptions = {
                url: 'https://httpbin.org/post',
                acceptedFiles: 'image/*',
                thumbnailWidth: 150,
                maxFilesize: 0.5,
                autoProcessQueue: false,
                addRemoveLinks: true,
                dictRemoveFile: 'X',
                resizeWidth: 100
            }
        },
        methods: {
            handleURL(str) {
                return JSON.parse(str.replace(/\'/g, '"'))
            },
            fetch() {
                if (this.itemID) {
                    searchModel('CheckList', {
                        search_keys: {
                            object_id: this.itemID,
                            model_name: this.model
                        },
                        order_by: 'id',
                        page_size: 2000
                    }).then( res => {
                        this.checkLists = res.data.list
                    } )
                } else {
                    searchModel('CheckList', {
                        search_keys: {
                            id: this.data.id
                        },
                        order_by: 'id',
                        page_size: 2000
                    }).then( res => {
                        this.checkLists = res.data.list
                    } )
                }

            },
            saveCheckList() {
                if (this.templateID) {
                    this.loading = true
                    createChecklistFromTemplate({
                        template_id: this.templateID,
                        model_name: this.model,
                        object_id: this.itemID,
                    }).then(  res => {
                        this.loading = false
                        this.fetch()
                    } ).catch(e => this.loading = false)
                }
            },
            removeCheckList(checklist) {
                swal({
                    title: "Are you sure?",
                    text: "Remove this item",
                    icon: "warning",
                    dangerMode: true,
                    buttons: true,
                }).then((willDelete) => {
                    if (willDelete) {
                        this.loading = true
                        deleteModel('CheckList', checklist.id).then(res => {
                            this.loading = false
                            this.fetch()
                        }).catch(e => {
                            this.loading = false
                        })
                    }
                })
            },
            fetchActive() {
                if (this.itemID) {
                    searchModel('Memo', {
                        search_keys: {
                            model_name: this.model,
                            object_id: this.itemID,
                        },
                        order_by: '-date',
                        page_size: 2000
                    }).then(res => {
                        this.activeItems = res.data.list
                    })
                }

            },
            toggleCompleted(item) {
                if (!this.itemID) return
                this.loading = true
                updateModel('CheckListItem', item.id, {
                    "is_completed": !item.is_completed,
                    "completion_time": moment().utc().format('YYYY-MM-DD HH:mm:ss'),
                    "completed_by": !item.is_completed ? this.$store.state.user : null
                }).then(res => {
                    this.loading = false
                    this.fetch()
                }).catch(e => this.loading = false)
            },
            add(checklist, text) {
                this.loading = true
                addModel('CheckListItem', {
                    'check_list': checklist.id,
                    'item_name': text,
                    "is_completed": false,
                    "completion_time": null,
                    "completed_by": null,
                }).then(res => {
                    this.loading = false
                    this.fetch()
                }).catch(e => this.loading = false)
            },
            save(item, text) {
                this.loading = true
                updateModel('CheckListItem', item.id, {
                    "item_name": text
                }).then(res => {
                    this.loading = false
                    this.fetch()
                }).catch(e => this.loading = false)
            },
            remove(item) {
                swal({
                    title: "Are you sure?",
                    text: "Remove this item",
                    icon: "warning",
                    dangerMode: true,
                    buttons: true,
                }).then((willDelete) => {
                    if (willDelete) {
                        this.loading = true
                        deleteModel('CheckListItem', item.id).then(res => {
                            this.loading = false
                            this.fetch()
                        }).catch(e => {
                            this.loading = false
                        })
                    }
                })
            },
            addedFiles(files) {
                for (let i = 0; i < files.length; i++) {
                    this.files.push(files[i])
                }
            },
            removeFile(file) {
                this._removeFileArr(this.files, file.upload.uuid)
            },
            saveActive() {

                if (!this.title.trim() || !this.desc.trim()) {
                    return $.toast({
                        heading: 'Please fill title and description',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error',
                    })
                }

                this.attachment_hook = []
                this.tmpFiles = $.extend([], this.files, true)
                this.loading = true
                if (this.tmpFiles.length) { // 有图片上传
                    this.files.forEach(file => {
                        getUploadInfo({
                            file_name: 'issue/' + file.name,
                            storage_type: 'PRIVATE',
                            file_size: file.size
                        }).then(res => {
                            let cloud_file_id = res.data.cloud_file_id
                            uploadFileToOss(file, res.data).then(res => {
                                if (cloud_file_id) {
                                    notifyFileUploadComplete({file_id: cloud_file_id}).then(res => {
                                        if (res.status == 200) {
                                            this.attachment_hook.push(cloud_file_id)
                                            this._removeFileArr(this.tmpFiles, file.upload.uuid)

                                            if (!this.tmpFiles.length) {
                                                addModel("Memo", {
                                                    "added_by": this.$store.state.user,
                                                    "attachments_hook": this.attachment_hook,
                                                    "model_name": this.model,
                                                    "object_id": this.itemID,
                                                    "title": this.title,
                                                    "text": this.desc,
                                                    "date": moment().utc().format('YYYY-MM-DD HH:mm:ss')
                                                }).then(res => {
                                                    this.loading = false
                                                    if (res.data.id) {
                                                        this.$refs.myVueDropzone.removeAllFiles()
                                                        this.files = []
                                                        this.title = ''
                                                        this.desc = ''
                                                        this.fetchActive()
                                                    }

                                                }).catch(e => this.loading = false)
                                            }
                                        } else {
                                            this.loading = false
                                        }
                                    })
                                }
                            }).catch(e => this.loading = false)
                        })
                    })
                } else {
                    addModel("Memo", {
                        "added_by": this.$store.state.user,
                        "model_name": this.model,
                        "object_id": this.itemID,
                        "title": this.title,
                        "text": this.desc,
                        "date": moment().utc().format('YYYY-MM-DD HH:mm:ss')
                    }).then(res => {
                        this.loading = false
                        if (res.data.id) {
                            this.title = ''
                            this.desc = ''
                            this.fetchActive()
                        }

                    }).catch(e => this.loading = false)
                }
            },
            updateActiveItem(item, text) {
                this.loading = true
                updateModel('Memo', item.id, {
                    "text": text
                }).then(res => {
                    this.loading = false
                    this.fetchActive()
                }).catch(e => this.loading = false)
            },
            _removeFileArr(arr, uuid) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].upload.uuid === uuid) {
                        arr.splice(i, 1)
                        break;
                    }
                }
            },
        },
        watch: {
            innerShow(val) {
                if (val) {
                    this.fetch()
                    this.fetchActive()
                    this.templateID = ''
                    this.checkLists = []
                    this.activeItems = []
                }
            }
        }
    }
</script>

<style scoped lang="stylus">
    .check-item
        .show
            display: none;
        .percent-text
            display: block;
            color: #6b808c;
            font-size: 11px;
            line-height: 10px;
            text-align: center;
            width: 50px;
            margin-bottom: 17px;
            margin-right: 4px;
        .btn-wrapper
            margin-top: 4px;
            .icon
                -webkit-appearance: none;
                padding: 0;
                cursor: pointer;
                background: 0 0;
                border: 0;
                font-size: 24px;
                font-weight: 700;
                line-height: 1;
                color: #000;
                text-shadow: 0 1px 0 #fff;
                opacity: .2;
                vertical-align: middle;
                margin-left: 4px;
            &:hover
                opacity: .8;
        .add-btn
            display: flex;
            cursor: pointer;
            &:hover
                color: lightskyblue
        .add-content
            display: none;
        .active-items
            .active-item
                .title
                    font-weight: bold;
                    .time
                        font-size: 12px;
                        font-weight: 400;
                        color: #6b808c
                .desc
                    margin: 10px;
                    background-color: #f5f6f7;
                    border-radius: 3px;
                    box-shadow: 0 0 0 1px rgba(9, 45, 66, .13);
                    margin: 12px 0;
                    padding: 8px 12px;
                    word-break: normal;
                    word-wrap: normal;
                    overflow-wrap: normal;
</style>